﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Data;
using DevExpress.Utils;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraEditors.DXErrorProvider;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraEditors.DXErrorProvider;
using System.Text.RegularExpressions;
using QuanLyKho.DKChung;

namespace QuanLyKho.PhongLenh
{
    public partial class Lss_LapLenh : Form
    {
        public static string MaID = "0";
        public static string IdSanPham = "0";
        public static bool xem = false;
        public string MaSanPham = "";

        public Lss_LapLenh()
        {
            InitializeComponent();
            Loaddata();
            SetPropertiesGrid();
        }

        public void Loaddata()
        {
            if (MaID == "0" && IdSanPham != "0")
            {
                LoadGrid();
                SetPropertiesColumns();
                DataTable dt = DataAll.SelectAll("PhongMau_SanPham", "*", "WHERE IdSanPham = " + IdSanPham);
                dtNgayLapLenh.Value = Convert.ToDateTime(dt.Rows[0]["NgayLL"]);
                txtSoLuong.EditValue = dt.Rows[0]["SoLuong"].ToString();
                MaSanPham = dt.Rows[0]["MaHang"].ToString();
                txtChungtu.Text = dt.Rows[0]["SoChungTu"].ToString();
                dtSXTuNgay.Value = Convert.ToDateTime(dt.Rows[0]["TuNgay"]);
                dtSXDenNgay.Value = Convert.ToDateTime(dt.Rows[0]["DenNgay"]);
                txtMaSP.Text = dt.Rows[0]["MaHang"].ToString();
                txtLoaiHang.Text = dt.Rows[0]["LoaiHang"].ToString();
                txtLanTai.Text = dt.Rows[0]["LanSanXuat"].ToString();
                txtSoLenh.Text = dt.Rows[0]["LenhSanXuat"].ToString();
            }
            else
            {
                SetPropertiesColumns();
                var data = DataAll.SelectAll("LenhSanXuat", "*", "WHERE ID =" + MaID);
                dtNgayLapLenh.Value = Convert.ToDateTime(data.Rows[0]["NgayLapLenh"]);
                txtSoLuong.Text = data.Rows[0]["SoLuong"].ToString();
                txtGhiChu.Text = data.Rows[0]["GhiChu"].ToString();
                dtNgayChungTu.Value = Convert.ToDateTime(data.Rows[0]["NgayChungTu"]);
                dtNgayHachToan.Value = Convert.ToDateTime(data.Rows[0]["NgayHoachToan"]);
                txtChungtu.Text = data.Rows[0]["SoChungTu"].ToString();
                DataTable dt = DataAll.SelectAll("PhongMau_SanPham", "*", "WHERE IdSanPham = " + data.Rows[0]["IdSanPham"].ToString());
                txtMaSP.Text = dt.Rows[0]["MaHang"].ToString();
                txtLoaiHang.Text = dt.Rows[0]["LoaiHang"].ToString();
                txtLanTai.Text = dt.Rows[0]["LanSanXuat"].ToString();
                txtSoLenh.Text = dt.Rows[0]["LenhSanXuat"].ToString();
                MaSanPham = dt.Rows[0]["MaHang"].ToString();
                var data2 = DataAll.SelectAll("LenhSanXuat_ChiTiet ct LEFT JOIN Kho_VatTu vt ON ct.MaVatTu = vt.MaVatTu",
                                              "vt.IDVatTu,ct.ID,[IDLenhSanXuat],ct.[MaVatTu],vt.MaVatTu as'Mã vật tư',[S],[M],[L],[XL]," +
                                              "[TongCan] as'Tổng cần', [DMTT] as'ĐMTT',[SoLuongCan] as'SL cần'," +
                                              "[DauTam] as'Đầu tấm',ct.[MoTa] as'Mô tả',ct.[GhiChu] as'Ghi chú', ct.[LoaiVatTu] as 'Loại vật tư'",
                                              " WHERE IDLenhSanXuat =" + MaID);
                data2.Rows.Add();
                gridChiTiet.DataSource = null;
                gridChiTiet.DataSource = data2;
                gvChiTiet.FocusedRowHandle = data.Rows.Count;

            }
            LoadImage();
        }

        public void SetPropertiesGrid()
        {
            gvChiTiet.OptionsView.ShowGroupPanel = false;
            gvChiTiet.OptionsView.NewItemRowPosition = NewItemRowPosition.None;
            gvChiTiet.OptionsView.ShowFooter = true;
            for (int i = 0; i < gvChiTiet.Columns.Count; i++)
            {
                gvChiTiet.Columns[i].OptionsColumn.AllowSort = DefaultBoolean.False;
            }
            gvChiTiet.Columns["IDVatTu"].Visible = false;
            gvChiTiet.Columns["Mô tả"].OptionsColumn.AllowEdit = false;
        }

        public void SetPropertiesColumns()
        {
            //Ma hang
            luMaVatTu.Properties.DataSource = DataAll.SelectAll("Kho_VatTuDuKien", "IDVatTuDuKien,MaVatTu,TenVatTu", "");
            luMaVatTu.Properties.Columns.Add(new LookUpColumnInfo("IDVatTuDuKien"));
            luMaVatTu.Properties.Columns.Add(new LookUpColumnInfo("MaVatTu"));
            luMaVatTu.Properties.Columns.Add(new LookUpColumnInfo("TenVatTu"));
            luMaVatTu.Properties.DisplayMember = "MaVatTu";
            luMaVatTu.Properties.ValueMember = "MaVatTu";
            luMaVatTu.Properties.NullText = "--- Chọn vật tư ---";
            luMaVatTu.Properties.TextEditStyle = TextEditStyles.DisableTextEditor;
            luMaVatTu.Properties.ShowHeader = false;
            luMaVatTu.Properties.Columns["IDVatTuDuKien"].Visible = false;

            // Loại vật tư
            DataTable dtLoaiVatTu = new DataTable("dsSiNO");
            dtLoaiVatTu.Columns.Add("LoaiVatTu", typeof(string));
            dtLoaiVatTu.Columns.Add("Value", typeof(int));
            dtLoaiVatTu.Rows.Add(Common.HienThiLoaiVatTu(Convert.ToInt32(LoaiVatTu.CatMay)), Convert.ToInt32(LoaiVatTu.CatMay));
            dtLoaiVatTu.Rows.Add(Common.HienThiLoaiVatTu(Convert.ToInt32(LoaiVatTu.HoanThien)), Convert.ToInt32(LoaiVatTu.HoanThien));

            luLoaiVatTu.Properties.DataSource = dtLoaiVatTu;
            luLoaiVatTu.Properties.Columns.Add(new LookUpColumnInfo("Value"));
            luLoaiVatTu.Properties.Columns.Add(new LookUpColumnInfo("LoaiVatTu"));
            luLoaiVatTu.Properties.DisplayMember = "LoaiVatTu";
            luLoaiVatTu.Properties.ValueMember = "Value";
            luLoaiVatTu.Properties.Columns["Value"].Visible = false;
            luLoaiVatTu.Properties.NullText = string.Empty;
            luLoaiVatTu.Properties.ShowHeader = false;

            luMaDangAnh.Properties.DataSource = DataAll.SelectAll("Kho_VatTu", "MaVatTu", "");
            luMaDangAnh.Properties.Columns.Add(new LookUpColumnInfo("MaVatTu"));
            luMaDangAnh.Properties.DisplayMember = "MaVatTu";
            luMaDangAnh.Properties.ValueMember = "MaVatTu";
            luMaDangAnh.Properties.TextEditStyle = TextEditStyles.DisableTextEditor;
            luMaDangAnh.Properties.NullText = "--- Chọn ảnh vật tư ---";
            luMaDangAnh.Properties.ShowHeader = false;

            //Format columns
            gcM.DisplayFormat.FormatType = FormatType.Custom;
            gcM.DisplayFormat.FormatString = "{0:0,0.00}";
            gcS.DisplayFormat.FormatType = FormatType.Numeric;
            gcS.DisplayFormat.FormatString = "{0:0,0.00}";
            gcL.DisplayFormat.FormatType = FormatType.Numeric;
            gcL.DisplayFormat.FormatString = "{0:0,0.00}";
            gcXL.DisplayFormat.FormatType = FormatType.Numeric;
            gcXL.DisplayFormat.FormatString = "{0:0,0.00}";
            gcDMTT.DisplayFormat.FormatType = FormatType.Numeric;
            gcDMTT.DisplayFormat.FormatString = "{0:0,0.00}";
            gcTongCan.DisplayFormat.FormatType = FormatType.Numeric;
            gcTongCan.DisplayFormat.FormatString = "{0:0,0.00}";
            gcSLCan.DisplayFormat.FormatType = FormatType.Numeric;
            gcSLCan.DisplayFormat.FormatString = "{0:0,0.00}";

            gcTongCan.OptionsColumn.AllowEdit = false;
            gcXoa.Width = 20;
            gcXoa.AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center;
            gcMaVatTu.AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center;
            gcS.AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center;
            gcM.AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center;
            gcL.AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center;
            gcXL.AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center;
            gcTongCan.AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center;
            gcDMTT.AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center;
            gcSLCan.AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center;
            gcDauTam.AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center;
            gcGhiChu.AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center;

            gcS.AppearanceCell.TextOptions.HAlignment = HorzAlignment.Center;
            gcM.AppearanceCell.TextOptions.HAlignment = HorzAlignment.Center;
            gcL.AppearanceCell.TextOptions.HAlignment = HorzAlignment.Center;
            gcXL.AppearanceCell.TextOptions.HAlignment = HorzAlignment.Center;
            gcTongCan.AppearanceCell.TextOptions.HAlignment = HorzAlignment.Center;
            gcDMTT.AppearanceCell.TextOptions.HAlignment = HorzAlignment.Center;
            gcSLCan.AppearanceCell.TextOptions.HAlignment = HorzAlignment.Center;

            bntLuLai.Visible = xem;
            if (!xem)
            {
                gvChiTiet.OptionsBehavior.Editable = false;
            }
        }

        public void LoadGrid()
        {
            var dataColumns = new DataTable();
            dataColumns.Columns.Add("IDVatTu");
            dataColumns.Columns.Add("Mã vật tư");
            dataColumns.Columns.Add("Mô tả");
            dataColumns.Columns.Add("S", typeof(double));
            dataColumns.Columns.Add("M", typeof(double));
            dataColumns.Columns.Add("L", typeof(double));
            dataColumns.Columns.Add("XL", typeof(double));
            dataColumns.Columns.Add("Tổng cần", typeof(double));
            dataColumns.Columns.Add("ĐMTT", typeof(double));
            dataColumns.Columns.Add("SL cần", typeof(double));
            dataColumns.Columns.Add("Đầu tấm");
            dataColumns.Columns.Add("Ghi chú");
            dataColumns.Columns.Add("Loại vật tư");

            pbAnh.Image = null;
            for (int i = 0; i < 1; i++)
            {
                dataColumns.Rows.Add("");
            }
            gridChiTiet.DataSource = null;
            gridChiTiet.DataSource = dataColumns;
        }

        public void LoadImage()
        {
            var data = DataAll.SelectAll("DkChung_HinhAnh", "*", " WHERE MaAnh='" + MaSanPham + "'");
            if (data.Rows.Count > 0)
            {
                var content = (byte[])data.Rows[0]["Anh"];
                if (content != null)
                {
                    Image newImage;
                    using (var ms = new MemoryStream(content, 0, content.Length))
                    {
                        ms.Write(content, 0, content.Length);
                        newImage = Image.FromStream(ms, true);
                    }
                    pbAnh.Image = newImage;
                }
                else
                {
                    pbAnh.Image = null;
                }
            }
            else
            {
                MessageBox.Show("Không tìm thấy mã ảnh", "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void bntLuLai_Click(object sender, EventArgs e)
        {
            if (gvChiTiet.RowCount <= 1)
            {
                MessageBox.Show("Vui lòng chọn vật tư !", "Lỗi nhập dữ liệu", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (MaID != "0")
            {
                if (gvChiTiet.RowCount > 1)
                {
                    string message = string.Empty;
                    message = DataAll.Update("LenhSanXuat", "NguoiLapLenh=N'" + Main.UserID + "',SoLuong=" + txtSoLuong.Text
                        + ",NgayChungTu=N'" + dtNgayChungTu.Value.ToString("MM/dd/yyyy") + "',NgayHoachToan=N'" + dtNgayHachToan.Value.ToString("MM/dd/yyyy") + "',GhiChu=N'"
                        + txtGhiChu.Text + "' WHERE ID =" + MaID);
                    if (message == "success")
                    {
                        var dataview = (DataView)gvChiTiet.DataSource;
                        for (int i = 0; i < gvChiTiet.RowCount - 1; i++)
                        {
                            var mahang = (DataRowView)luMaVatTu.GetDataSourceRowByKeyValue(gcMaVatTu.View.GetRowCellValue(i, "Mã vật tư").ToString());
                            var loaivattu = (DataRowView)luLoaiVatTu.GetDataSourceRowByKeyValue(gcMaVatTu.View.GetRowCellValue(i, "Loại vật tư").ToString());
                            if (string.IsNullOrEmpty(gvChiTiet.GetRowCellValue(i, "ID").ToString()))
                            {
                                message = DataAll.InsertAll("LenhSanXuat_ChiTiet", MaID + "," + mahang.Row.ItemArray[1]
                                    + "," + gcS.View.GetRowCellValue(i, "S")
                                    + "," + gcM.View.GetRowCellValue(i, "M")
                                    + "," + gcL.View.GetRowCellValue(i, "L")
                                    + "," + gcXL.View.GetRowCellValue(i, "XL")
                                    + "," + 0
                                    + "," + gcDMTT.View.GetRowCellValue(i, "ĐMTT")
                                    + "," + gcTongCan.View.GetRowCellValue(i, "Tổng cần")
                                    + "," + gcSLCan.View.GetRowCellValue(i, "SL cần")
                                    + "," + gcDauTam.View.GetRowCellValue(i, "Đầu tấm")
                                    + "," + gcMoTa.View.GetRowCellValue(i, "Mô tả")
                                    + "," + gcGhiChu.View.GetRowCellValue(i, "Ghi chú")
                                    + "," + loaivattu.Row.ItemArray[1]);
                                // cap nhat so luong
                                var soluong = DataAll.SelectAll("Kho_VatTuDuKien", "SoLuong",
                                           " WHERE MaVatTu=N'" + gvChiTiet.GetDataRow(i)["Mã vật tư"] + "'");
                                message = DataAll.Update("Kho_VatTuDuKien", "SoLuong = " + Convert.ToString(Convert.ToInt32(soluong.Rows[0]["SoLuong"]) - Convert.ToInt32(gvChiTiet.GetDataRow(i)["SL cần"])) + " WHERE MaVatTu=N'" + gvChiTiet.GetDataRow(i)["Mã vật tư"] + "'");



                                if (message != "success")
                                {
                                    break;
                                }
                            }
                            else
                            {
                                // cap nhat so luong
                                var soluongcu = DataAll.SelectAll("LenhSanXuat_ChiTiet", "SoLuongCan", " WHERE ID = " + gvChiTiet.GetRowCellValue(i, "ID"));
                                var soluongkho = DataAll.SelectAll("Kho_VatTuDuKien", "SoLuong", " WHERE MaVatTu=N'" + gvChiTiet.GetDataRow(i)["Mã vật tư"] + "'");
                                var soluongcapnhat = (Convert.ToInt32(soluongkho.Rows[0]["SoLuong"]) + Convert.ToInt32(soluongcu.Rows[0]["SoLuongCan"])) - Convert.ToInt32(gvChiTiet.GetRowCellValue(i, "SL cần"));
                                message = DataAll.Update("Kho_VatTuDuKien", "SoLuong = " + soluongcapnhat + " WHERE MaVatTu=N'" + gvChiTiet.GetDataRow(i)["Mã vật tư"] + "'");

                                message = DataAll.Update("LenhSanXuat_ChiTiet", "MaVatTu=N'" + mahang.Row.ItemArray[1]
                                    + "',S=N'" + gcS.View.GetRowCellValue(i, "S") + "',M=N'" + gcS.View.GetRowCellValue(i, "M")
                                    + "',L=N'" + gcS.View.GetRowCellValue(i, "L") + "',XL=N'" + gcS.View.GetRowCellValue(i, "XL")
                                    + "',DMTT=N'" + gcS.View.GetRowCellValue(i, "ĐMTT")
                                    + "',TongCan=N'" + gcS.View.GetRowCellValue(i, "Tổng cần") + "',SoLuongCan=N'" + gcS.View.GetRowCellValue(i, "SL cần")
                                    + "',DauTam=N'" + gcS.View.GetRowCellValue(i, "Đầu tấm") + "',MoTa=N'" + gcS.View.GetRowCellValue(i, "Mô tả")
                                    + "',GhiChu=N'" + gcS.View.GetRowCellValue(i, "Ghi chú") + "', LoaiVatTu = " + loaivattu.Row.ItemArray[1] + " WHERE ID =" + dataview[i]["ID"]);

                            }
                            if (message != "success")
                            {
                                break;
                            }
                        }
                    }
                    MessageBox.Show(message.Equals("success") ? "Sửa lệnh thành công" : message, "Message",
                                    MessageBoxButtons.OK,
                                    message.Equals("success") ? MessageBoxIcon.Information : MessageBoxIcon.Error);
                    Close();
                }
            }
            else
            {
                if (gvChiTiet.RowCount > 1)
                {
                    string message = string.Empty;
                    var data = DataAll.SelectCustomer("INSERT INTO [LenhSanXuat] VALUES(" + IdSanPham + ",'"
                        + dtNgayLapLenh.Value.ToString("MM/dd/yyyy") + "','" + Main.UserID + "',"
                        + txtSoLuong.Text + ",'" + DateTime.Now.ToString("MM/dd/yyyy") + "','"
                        + DateTime.Now.ToString("MM/dd/yyyy") + "','" + DateTime.Now.ToString("MM/dd/yyyy") + "'," + Convert.ToInt32(TrangThai.LenhSanXuat_TaoMoi) + ",'"
                        + dtNgayChungTu.Value.ToString("MM/dd/yyyy") + "','"
                        + dtNgayHachToan.Value.ToString("MM/dd/yyyy") + "','"
                        + txtChungtu.Text + "','"
                        + txtGhiChu.Text + "',N'"
                        + "Phòng lệnh" + "',N'"
                        + "Phòng cắt" + "','"
                        + Convert.ToDateTime(dtSXTuNgay.Value).ToString("MM/dd/yyyy") + "','"
                        + Convert.ToDateTime(dtSXDenNgay.Value).ToString("MM/dd/yyyy") + "','"
                        + DateTime.Now.ToString("MM/dd/yyyy") + "') SELECT MAX(ID) FROM LenhSanXuat");
                    for (int i = 0; i < gvChiTiet.RowCount - 1; i++)
                    {
                        var id_vattu = (DataRowView)luMaVatTu.GetDataSourceRowByKeyValue(gcMaVatTu.View.GetRowCellValue(i, "Mã vật tư").ToString());
                        var loaivattu = (DataRowView)luLoaiVatTu.GetDataSourceRowByKeyValue(gcMaVatTu.View.GetRowCellValue(i, "Loại vật tư").ToString());
                        message = DataAll.InsertAll("LenhSanXuat_ChiTiet", data.Rows[0][0] + "," + id_vattu.Row.ItemArray[1]
                            + "," + gcS.View.GetRowCellValue(i, "S")
                            + "," + gcM.View.GetRowCellValue(i, "M")
                            + "," + gcL.View.GetRowCellValue(i, "L")
                            + "," + gcXL.View.GetRowCellValue(i, "XL")
                            + "," + 0
                            + "," + gcDMTT.View.GetRowCellValue(i, "ĐMTT")
                            + "," + gcTongCan.View.GetRowCellValue(i, "Tổng cần")
                            + "," + gcSLCan.View.GetRowCellValue(i, "SL cần")
                            + "," + gcDauTam.View.GetRowCellValue(i, "Đầu tấm")
                            + "," + gcMoTa.View.GetRowCellValue(i, "Mô tả")
                            + "," + gcGhiChu.View.GetRowCellValue(i, "Ghi chú")
                            + "," + loaivattu.Row.ItemArray[1]);
                        // cap nhat so luong
                        var soluong = DataAll.SelectAll("Kho_VatTuDuKien", "SoLuong",
                                                " WHERE MaVatTu=N'" + gvChiTiet.GetDataRow(i)["Mã vật tư"] + "'");
                        message = DataAll.Update("Kho_VatTuDuKien", "SoLuong = " + Convert.ToString(Convert.ToInt32(soluong.Rows[0]["SoLuong"]) - Convert.ToInt32(gvChiTiet.GetDataRow(i)["SL cần"])) + " WHERE MaVatTu=N'" + gvChiTiet.GetDataRow(i)["Mã vật tư"] + "'");

                        if (message != "success")
                        {
                            DataAll.Delete("LenhSanXuat_ChiTiet", "WHERE IDLenhSanXuat=" + data.Rows[0][0]);
                            break;
                        }
                    }
                    MessageBox.Show(message.Equals("success") ? "Tạo lệnh thành công!" : message, "Message",
                                    MessageBoxButtons.OK,
                                    message.Equals("success") ? MessageBoxIcon.Information : MessageBoxIcon.Error);
                    message = DataAll.Update("PhongMau_SanPham", "TrangThai = " + Convert.ToInt32(TrangThai.PhongMau_PhongLenhDaTaoLenh) + " WHERE IdSanPham = " + IdSanPham);
                    Close();

                }

            }
        }

        private void btnThoat_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void gvChiTiet_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (e.Column.Caption == "Mã vật tư")
            {
                if (e.RowHandle == gvChiTiet.RowCount - 1)
                {
                    (gridChiTiet.MainView as GridView).AddNewRow();
                }
                var vatTu = (DataRowView)luMaVatTu.GetDataSourceRowByKeyValue(e.Value);
                gvChiTiet.SetRowCellValue(e.RowHandle, gvChiTiet.Columns["Mô tả"], vatTu.Row.ItemArray[2].ToString());
                gvChiTiet.SetRowCellValue(e.RowHandle, gvChiTiet.Columns["S"], 0);
                gvChiTiet.SetRowCellValue(e.RowHandle, gvChiTiet.Columns["M"], 0);
                gvChiTiet.SetRowCellValue(e.RowHandle, gvChiTiet.Columns["L"], 0);
                gvChiTiet.SetRowCellValue(e.RowHandle, gvChiTiet.Columns["XL"], 0);
                gvChiTiet.SetRowCellValue(e.RowHandle, gvChiTiet.Columns["ĐMTT"], 0);
                gvChiTiet.SetRowCellValue(e.RowHandle, gvChiTiet.Columns["Tổng cần"], 0);
                gvChiTiet.SetRowCellValue(e.RowHandle, gvChiTiet.Columns["SL cần"], 0);
                gvChiTiet.SetRowCellValue(e.RowHandle, gvChiTiet.Columns["Loại vật tư"], Convert.ToInt32(LoaiVatTu.CatMay));
                //check use
                var data = (DataView)gvChiTiet.DataSource;
                if (data.Count > 2)
                {
                    for (int i = 0; i < data.Count - 1; i++)
                    {
                        if (i != e.RowHandle)
                        {
                            if (gvChiTiet.GetRowCellValue(e.RowHandle, "Mã vật tư").ToString() == data.Table.Rows[i]["Mã vật tư"].ToString())
                            {
                                MessageBox.Show("Nhập trùng giá trị " + gvChiTiet.GetRowCellValue(e.RowHandle, "Mã vật tư"), "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                if (e.RowHandle == gvChiTiet.RowCount - 2)
                                {
                                    (gridChiTiet.MainView as GridView).DeleteRow(e.RowHandle);
                                }
                                else
                                {
                                    gvChiTiet.SetRowCellValue(e.RowHandle, "Mã vật tư", "");
                                }
                                break;
                            }
                        }
                    }
                }
            }

            if (e.Column.Caption == "S" && !string.IsNullOrEmpty(gvChiTiet.GetRowCellValue(e.RowHandle, gvChiTiet.Columns["S"]).ToString())
           && !string.IsNullOrEmpty(gvChiTiet.GetRowCellValue(e.RowHandle, gvChiTiet.Columns["M"]).ToString())
           && !string.IsNullOrEmpty(gvChiTiet.GetRowCellValue(e.RowHandle, gvChiTiet.Columns["L"]).ToString())
           && !string.IsNullOrEmpty(gvChiTiet.GetRowCellValue(e.RowHandle, gvChiTiet.Columns["XL"]).ToString()))
            {
                gvChiTiet.SetRowCellValue(e.RowHandle, gvChiTiet.Columns["Tổng cần"], Convert.ToDouble(gvChiTiet.GetRowCellValue(e.RowHandle, "Số lượng"))
                    + Convert.ToDouble(gvChiTiet.GetRowCellValue(e.RowHandle, "S"))
                    + Convert.ToDouble(gvChiTiet.GetRowCellValue(e.RowHandle, "M"))
                    + Convert.ToDouble(gvChiTiet.GetRowCellValue(e.RowHandle, "L"))
                    + Convert.ToDouble(gvChiTiet.GetRowCellValue(e.RowHandle, "XL")));
            }

            if (e.Column.Caption == "M" && !string.IsNullOrEmpty(gvChiTiet.GetRowCellValue(e.RowHandle, gvChiTiet.Columns["S"]).ToString())
           && !string.IsNullOrEmpty(gvChiTiet.GetRowCellValue(e.RowHandle, gvChiTiet.Columns["M"]).ToString())
           && !string.IsNullOrEmpty(gvChiTiet.GetRowCellValue(e.RowHandle, gvChiTiet.Columns["L"]).ToString())
           && !string.IsNullOrEmpty(gvChiTiet.GetRowCellValue(e.RowHandle, gvChiTiet.Columns["XL"]).ToString()))
            {
                gvChiTiet.SetRowCellValue(e.RowHandle, gvChiTiet.Columns["Tổng cần"], Convert.ToDouble(gvChiTiet.GetRowCellValue(e.RowHandle, "Số lượng"))
                    + Convert.ToDouble(gvChiTiet.GetRowCellValue(e.RowHandle, "S"))
                    + Convert.ToDouble(gvChiTiet.GetRowCellValue(e.RowHandle, "M"))
                    + Convert.ToDouble(gvChiTiet.GetRowCellValue(e.RowHandle, "L"))
                    + Convert.ToDouble(gvChiTiet.GetRowCellValue(e.RowHandle, "XL")));
            }

            if (e.Column.Caption == "L" && !string.IsNullOrEmpty(gvChiTiet.GetRowCellValue(e.RowHandle, gvChiTiet.Columns["S"]).ToString())
           && !string.IsNullOrEmpty(gvChiTiet.GetRowCellValue(e.RowHandle, gvChiTiet.Columns["M"]).ToString())
           && !string.IsNullOrEmpty(gvChiTiet.GetRowCellValue(e.RowHandle, gvChiTiet.Columns["L"]).ToString())
           && !string.IsNullOrEmpty(gvChiTiet.GetRowCellValue(e.RowHandle, gvChiTiet.Columns["XL"]).ToString()))
            {
                gvChiTiet.SetRowCellValue(e.RowHandle, gvChiTiet.Columns["Tổng cần"], Convert.ToDouble(gvChiTiet.GetRowCellValue(e.RowHandle, "Số lượng"))
                    + Convert.ToDouble(gvChiTiet.GetRowCellValue(e.RowHandle, "S"))
                    + Convert.ToDouble(gvChiTiet.GetRowCellValue(e.RowHandle, "M"))
                    + Convert.ToDouble(gvChiTiet.GetRowCellValue(e.RowHandle, "L"))
                    + Convert.ToDouble(gvChiTiet.GetRowCellValue(e.RowHandle, "XL")));
            }

            if (e.Column.Caption == "XL" && !string.IsNullOrEmpty(gvChiTiet.GetRowCellValue(e.RowHandle, gvChiTiet.Columns["S"]).ToString())
           && !string.IsNullOrEmpty(gvChiTiet.GetRowCellValue(e.RowHandle, gvChiTiet.Columns["M"]).ToString())
           && !string.IsNullOrEmpty(gvChiTiet.GetRowCellValue(e.RowHandle, gvChiTiet.Columns["L"]).ToString())
           && !string.IsNullOrEmpty(gvChiTiet.GetRowCellValue(e.RowHandle, gvChiTiet.Columns["XL"]).ToString()))
            {
                gvChiTiet.SetRowCellValue(e.RowHandle, gvChiTiet.Columns["Tổng cần"], Convert.ToDouble(gvChiTiet.GetRowCellValue(e.RowHandle, "Số lượng"))
                    + Convert.ToDouble(gvChiTiet.GetRowCellValue(e.RowHandle, "S"))
                    + Convert.ToDouble(gvChiTiet.GetRowCellValue(e.RowHandle, "M"))
                    + Convert.ToDouble(gvChiTiet.GetRowCellValue(e.RowHandle, "L"))
                    + Convert.ToDouble(gvChiTiet.GetRowCellValue(e.RowHandle, "XL")));
            }
            if (e.Column.Caption == "ĐMTT" && !string.IsNullOrEmpty(gvChiTiet.GetRowCellValue(e.RowHandle, gvChiTiet.Columns["Tổng cần"]).ToString())
                && !string.IsNullOrEmpty(gvChiTiet.GetRowCellValue(e.RowHandle, gvChiTiet.Columns["ĐMTT"]).ToString()))
            {
                gvChiTiet.SetRowCellValue(e.RowHandle, gvChiTiet.Columns["SL cần"], Convert.ToDouble(gvChiTiet.GetRowCellValue(e.RowHandle, "Tổng cần")) * Convert.ToDouble(gvChiTiet.GetRowCellValue(e.RowHandle, "ĐMTT")));
            }
            if (e.Column.Caption == "Tổng cần" && !string.IsNullOrEmpty(gvChiTiet.GetRowCellValue(e.RowHandle, gvChiTiet.Columns["Tổng cần"]).ToString())
                && !string.IsNullOrEmpty(gvChiTiet.GetRowCellValue(e.RowHandle, gvChiTiet.Columns["ĐMTT"]).ToString()))
            {
                gvChiTiet.SetRowCellValue(e.RowHandle, gvChiTiet.Columns["SL cần"], Convert.ToDouble(gvChiTiet.GetRowCellValue(e.RowHandle, "Tổng cần")) * Convert.ToDouble(gvChiTiet.GetRowCellValue(e.RowHandle, "ĐMTT")));
            }
        }

        private void buttonDelete_ButtonClick(object sender, ButtonPressedEventArgs e)
        {
            if (gvChiTiet.FocusedRowHandle == gvChiTiet.RowCount - 1)
            {
                return;
            }

            DialogResult dialogResult = MessageBox.Show("Bạn có chắc chắn muốn xóa.", "Message", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

            if (dialogResult == DialogResult.Yes)
            {
                var dataview = (DataView)gvChiTiet.DataSource;
                if (MaID != "0")
                {
                    if (!string.IsNullOrEmpty(gvChiTiet.GetRowCellValue(gvChiTiet.FocusedRowHandle, "ID").ToString()))
                    {
                        // cap nhat so luong
                        var soluongcu = DataAll.SelectAll("LenhSanXuat_ChiTiet", "SoLuongCan", " WHERE ID = " + gvChiTiet.GetRowCellValue(gvChiTiet.FocusedRowHandle, "ID"));
                        var soluongkho = DataAll.SelectAll("Kho_VatTuDuKien", "SoLuong", " WHERE MaVatTu=N'" + gvChiTiet.GetDataRow(gvChiTiet.FocusedRowHandle)["Mã vật tư"] + "'");
                        var soluongcapnhat = (Convert.ToInt32(soluongkho.Rows[0]["SoLuong"]) + Convert.ToInt32(soluongcu.Rows[0]["SoLuongCan"]));
                        DataAll.Update("Kho_VatTuDuKien", "SoLuong = " + soluongcapnhat + " WHERE MaVatTu=N'" + gvChiTiet.GetDataRow(gvChiTiet.FocusedRowHandle)["Mã vật tư"] + "'");

                        string message = DataAll.Delete("LenhSanXuat_ChiTiet", " ID = " + dataview[gvChiTiet.FocusedRowHandle]["ID"]);
                        MessageBox.Show(message.Equals("success") ? "Xóa thành công" : message, "Message",
                                            MessageBoxButtons.OK,
                                            message.Equals("success") ? MessageBoxIcon.Information : MessageBoxIcon.Error);
                    }
                }
                (gridChiTiet.MainView as GridView).DeleteSelectedRows();
            }
        }

        private void pbAnh_Click(object sender, EventArgs e)
        {
            XemAnh.MaID = txtMaSP.Text;
            var anh = new XemAnh();
            anh.ShowDialog();
            XemAnh.MaID = "0";
        }

        private void luMaDangAnh_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13 && luMaDangAnh.EditValue!= null)
            {
                XemAnh.MaID = luMaDangAnh.EditValue.ToString();
                var anh = new XemAnh();
                anh.ShowDialog();
                XemAnh.MaID = "0";
            }
        }

        private void bntLuuTTChung_Click(object sender, EventArgs e)
        {
            string message = DataAll.Update("PhongMau_SanPham", " NgayLL=N'" + dtNgayLapLenh.Value.ToString("MM/dd/yyyy") + "', LenhSanXuat='" + txtSoLenh.Text
                + "', SoLuong='" + txtSoLuong.Text + "', SLConLai='" + txtSoLuong.Text + "' WHERE IdSanPham=" + IdSanPham);
            MessageBox.Show(message.Equals("success") ? "Sửa thông tin chung thành công" : message, "Message",
                        MessageBoxButtons.OK,
                        message.Equals("success") ? MessageBoxIcon.Information : MessageBoxIcon.Error);
        }

        private void bntExport_Click(object sender, EventArgs e)
        {
            var title = new DataTable();
            var content = new DataTable();
            var bottom = new DataTable();
            var saveFile = new SaveFileDialog();
            saveFile.Filter = "Excel Workbook (*.xlsx)|*.xlsx|Excel 97-2003 Workbook (*.xls)|*.xls|All files (*.*)|*.*";
            if (saveFile.ShowDialog() == DialogResult.OK)
            {
                for (int i = 0; i < 16; i++)
                {
                    title.Columns.Add("" + i);
                    content.Columns.Add("" + i);
                    bottom.Columns.Add("" + i);
                }
                title.Rows.Add("CHIC-LAND", "", "", "LỆNH SẢN XUẤT");
                title.Rows.Add("Kho: VẬT TƯ - HÀNG HÓA", "", "", "", "Ngày thang nam");
                title.Rows.Add("Từ NSX: " + txtKhoDen.Text, "", "");
                title.Rows.Add("Đến Kho: " + txtKhoDi.Text, "", "");
                title.Rows.Add("Ghi chú", "", "");
                title.Rows.Add("");
                title.Rows.Add("STT", "Mã vật tư", "Tên vật tư", "Đơn vị", "Khổ vải", "Q.C Giac", "Số lượng", "S", "M", "L", "XL","Tổng","DMTT","SL Cần","Đầu tấm","Ghi chú");
                var dtv = DataAll.SelectAll("Kho_VatTu", "*", "");
                for (int i = 0; i < gvChiTiet.RowCount - 1; i++)
                {
                    DataRow[] result = dtv.Select("IDVatTu=" + gvChiTiet.GetRowCellDisplayText(i, "IDVatTu"));
                    content.Rows.Add(i, result[0].ItemArray[2], result[0].ItemArray[3], result[0].ItemArray[7], result[0].ItemArray[13], result[0].ItemArray[10]
                        , result[0].ItemArray[6], gvChiTiet.GetRowCellDisplayText(i, "S"),gvChiTiet.GetRowCellDisplayText(i, "M"),gvChiTiet.GetRowCellDisplayText(i, "L")
                        , gvChiTiet.GetRowCellDisplayText(i, "XL"), gvChiTiet.GetRowCellDisplayText(i, "Tổng cần"),gvChiTiet.GetRowCellDisplayText(i, "ĐMTT"),
                        gvChiTiet.GetRowCellDisplayText(i, "SL cần"), gvChiTiet.GetRowCellDisplayText(i, "Đầu tấm"), gvChiTiet.GetRowCellDisplayText(i, "Ghi chú"));
                }

                //bottom.Rows.Add("* Tổng số tiền (viết bằng chữ): ");
                //bottom.Rows.Add("* Tổng số tiền (viết bằng chữ): ");
                bottom.Rows.Add("");
                bottom.Rows.Add("", "Quản lý", "", "Thành phẩm", "", "Hoàn thiện", "", "KCS", "", "May G.Công", "", "Cắt SP", "", "Kho V.Tư", "", "Lập lệnh");
                bottom.Rows.Add("", "");

                try
                {
                    ExportExcel.LenhSanXuat("Lệnh Sản Xuất", saveFile.FileName, title, content, bottom);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Lỗi Export", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

            }
        }

    }
}
